import User from 'utils/user';
import Util from 'utils/utils';
import Data from 'utils/data';
import { Event } from 'utils/event.js'
const EventMap = new Util.HashMap();
App({
  globalData: {
    channel:{
      ekey:'',
      fstr:''
    },
    userInfo: null,
    token:null,
    tempParam:null,
    phoneLogin:false,
    themeData:[],
    trackData:[],
    pageConfig:{}
  },
  event: new Event(), // 小程序跨页面通信: 发布／订阅模式
  isHide:false,
  logInstance:null,
  onError:function(e){
    Util.log('运行错误：',e);
  },
  onHide:function(){
    console.log('on hide');
    this.isHide = true;
    Util.trackPut({
      openBi:true,
      flush:true
    });
  },
  onShow:function(e){
    if(this.isHide === true){
      Util.log('切入显示',e);
      this.isHide = false;
      if(e.path == "pages/home/index/index"){
        /**
         * 打开首页时重置跟踪信息
         */
        let t = wx.getLaunchOptionsSync();
        console.log('LaunchOptions:',t);
        Util.setChannel(e.query);
      }
      Util.trackPut({
        openBi:true,
        firstVisit:1
      });
    }

    // 解决各类回调的兼容问题    二维码验证
    if (!this.captchaTicketExpire) this.captchaTicketExpire = {};
    // e.scene === 1038 &&
    if (e.referrerInfo.appId === 'wx5a3a7366fd07e119') {
      console.log('验证码回调', e)
      const result = e.referrerInfo.extraData;
      if (result.ret === 0) {
        const ticket = result.ticket;
        if (!this.captchaTicketExpire[ticket]) {
          this.captchaResult = result;
          this.captchaTicketExpire[ticket] = true;
        }
      } else {
        // 用户关闭了验证码
        console.log('用户关闭',e)
      }
    }
  },
  onLaunch: function (options) {
    let self  = this;
    let query = options.query;
    self.logInstance = wx.getLogManager({level: 1});
    Util.log(options);
    if(JSON.stringify(query) === '{}'){
      /**
       * 如果启动没有参数，清空本地跟踪源
       */
      Util.cache_remove('channel_2');
      self.globalData.channel = {
        ekey:'',
        fstr:'',
      };
    }

    Util.cache_put('mAuth',false);
    //主动更新检测
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager();
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                Util.log('success', res);
                if (res.confirm) {
                  updateManager.applyUpdate()
                }
              }
            });
          });
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
            });
          });
        }
      });
    }
    /**
     * 扩展Page的方法
     */
    const xhbPage = Page;
    Page = function(config) {

      config.data = self.extend(config.data,{
        static_host:Util.pageUrl + 'mini',
      });

      config.options = {};
      /**
       * 用户资料
       * @type {{}}
       */
      config.userInfo = {};
      /**
       * 是否完成登录
       * @type {boolean}
       */
      config.initUser = false;
      /**
       * 是否自动登录
       * @type {boolean}
       */
      config.autoAuth = config.autoAuth || false;
      /**
       * 分享配置
       * @type {boolean}
       */
      config.shareOption = config.shareOption || {
        title:false,
        imageUrl:false,
        path:false
      };
      /**
       * 页面跳转
       * @param event
       * data-page:跳转URL
       * data-type:page,tabar
       */
      config.toPage = config.toPage || function (event) {
        Util.toPage(event);
      };
      /**
       * 复制文本内容
       * @param event
       * data-text:要复制的文本
       */
      config.copyText = config.copyText || function (event) {
        if(event.currentTarget.dataset.text){
          wx.setClipboardData({
            data: event.currentTarget.dataset.text + ''
          });
        }
      };
      /**
       * 拨打电话
       * @param event
       * data-phone:要拨打的电话
       */
      config.callPhone = config.callPhone || function (event) {
        if(event.currentTarget.dataset.phone){
          wx.makePhoneCall({
            phoneNumber: event.currentTarget.dataset.phone
          });
        }
      };
      /**
       * 返回顶部
       * @type {*|Function}
       */
      config.backTop = config.backTop || function(){
        // 控制滚动
        wx.pageScrollTo({
          scrollTop: 0
        })
      };
      /**
       * 图片加载失败处理
       * @type {*|Function}
       */
      config.imgNotFound = config.imgNotFound || function(e){
        Util.log(e);
        let _errImg = e.target.dataset.img;
        let _errObj = {};
        _errObj[_errImg] = "/images/default_img.png";
        this.setData(_errObj)
      };
      /**
       * 更新用户资料
       * @param userInfo
       */
      config.updateUserInfo = function (userInfo) {
        let app = getApp();
        app.globalData.userInfo = userInfo;
        self.userInfo = userInfo;
      };
      /**
       * 重写页面载入方法(统一实现用户登录授权逻辑)
       * @param options
       */
      config.onLoad = function(options){
        let self  = this;
        let app   = getApp();
        let mAuth = false;
        /**
         * 处理二维码场景值
         */
        console.log('options',options);
        if(options.hasOwnProperty('scene')){
          options.scene = decodeURIComponent(options.scene);
          let scene = options.scene.split('/');
          if(scene && scene[0] === 'ekey' && !options.hasOwnProperty('ekey')){
            options.ekey = scene[1];
          }else{
            if(scene && scene[0].indexOf('_') > -1 && !options.hasOwnProperty('ekey')){
              options.ekey = scene[0];
            }
            if(scene.length > 0 && !options.hasOwnProperty('id')){
              options.id = scene[1];
            }
            if(scene.length === 1 && !options.hasOwnProperty('uid')){
              options.uid = scene[0];
            }
            if(scene.length === 3 && !options.hasOwnProperty('aid')){
              options.aid = scene[2];
            }
          }
        }
        Util.setChannel(options);
        self.options = options;
        /**
         * 需要自动登录时.直接开始登录流程
         */
        mAuth = Util.cache_get('disable_auto_login',false);
        if(self.autoAuth === true){
          if(mAuth === false){
            self.getUserInfo(function (userInfo) {
              /**
               * 已授权的用户自动登录成功
               */
              self.userInfo = userInfo;
              self.initUser = true;
              self.setData({
                userInfo:self.userInfo,
                openLogin:false,
                initUser:self.initUser
              });
              app.globalData.userInfo = userInfo;
              self.isTabBar && wx.showTabBar({});
              self.initPage(options);
            },function () {
              /**
               * 未授权的用户快捷登录失败时打开登录界面引导
               */
              self.isTabBar && wx.hideTabBar({});
              wx.setNavigationBarTitle({title:'用户登录'});
              self.setData({
                initUser:false,
                openLogin:true,
                userInfo:{uid:0}
              });
            });
          }else{
            self.isTabBar && wx.hideTabBar({});
            wx.setNavigationBarTitle({title:'用户登录'});
            self.setData({
              initUser:false,
              openLogin:true,
              userInfo:{uid:0}
            });
          }
        }else{
          /**
           * 尝试验证已经登录过的用户
           */
          if(mAuth === false) {
            self.setData({
              userInfo: {uid:0}
            });
            User.tokenAuth(function (userInfo) {
              /**
               * 已授权的用户自动登录成功
               */
              self.userInfo = userInfo;
              self.initUser = true;
              self.setData({
                userInfo: self.userInfo,
                openLogin: false,
                initUser: self.initUser
              });
              app.globalData.userInfo = userInfo;
              self.isTabBar && wx.showTabBar({});
              self.initPage(options);
            }, function () {
              /**
               * 此处不自动登录了
               */
              self.initPage(options);
            }, 1);
          }else{
            self.initPage(options);
          }
        }
      };
      /**
       * 响应登录组件回调方法
       * @param res
       */
      config.loginSuccess = function(res){
        this.isTabBar && wx.showTabBar({});
        this.userInfo = res.detail;
        this.initUser = true;
        this.setData({
          initUser:true,
          openLogin:false,
          userInfo:res.detail
        });
        this.title && wx.setNavigationBarTitle({
          title:this.title
        });
        Util.cache_remove('disable_auto_login');
        this.initPage(this.options);
      };
      config.onShow = config.onShow || function(){
        try{
          if(this.isTabBar && this.data.initPage === true){
            wx.showTabBar();
          }
        }catch (e) {
        }
      };
      /**
       * 获取用户资料
       * @param success
       * @param login
       * @param up
       */
      config.getUserInfo = function (success, login,up) {
        let update = up || false;
        let app    = getApp();
        let self   = this;
        let mAuth  = Util.cache_get('disable_auto_login',false);
        if(mAuth !== false){
          login && login({});
          return true;
        }
        if (app.globalData.userInfo === null || update === true){
          User.login(function (userInfo) {
            self.userInfo = userInfo;
            self.setData({
              'userInfo':userInfo
            });
            app.globalData.userInfo = userInfo;
            success && success(userInfo);
          }, function (res) {
            login && login(res);
          },update);
        }else{
          success && success(app.globalData.userInfo);
        }
      };
      /**
       * 打开弹出层
       */
      config.openPopup = config.openPopup || function (e) {
        let type = e.currentTarget.dataset.type;
        let setD = {};
        if(this.data.hasOwnProperty(type)){
          setD[type] = true;
          this.setData(setD);
        }
      };
      /**
       * 关闭弹出层
       */
      config.closePopup = config.closePopup || function (e) {
        let type = e.currentTarget.dataset.type;
        let setD = {};
        console.log(type);
        if(this.data.hasOwnProperty(type)){
          setD[type] = false;
          console.log(setD);
          this.setData(setD);
        }
      };
      /**
       * 统一配置一个分享处理
       */
      config.onShareAppMessage = config.onShareAppMessage || function () {
        let _param,pages,currentPage;
        let _share  = this.shareOption;
        let channel = User.getShareParam(0);
        if(!_share.title){
          _share['title'] = '快来领取优惠券吧';
        }
        if(!_share.path){
          pages = getCurrentPages();
          currentPage = pages[pages.length - 1];
          _share['path'] = currentPage.route;
        }
        if(_share['path'].indexOf('?') === -1){
          _share['path'] += '?v=' + Util.version;
        }
        if(channel.hasOwnProperty('ekey') && channel.ekey && _share['path'].indexOf('ekey') === -1){
          _share['path'] += '&ekey=' + channel['ekey'];
        }
        if(channel.hasOwnProperty('shareUid') && channel.shareUid > 0 && _share['path'].indexOf('uid') === -1){
          _share['path'] += '&uid=' + channel['shareUid'];
        }
        _param = {
          title:_share['title'],
          path:_share['path']
        };
        if(_share['imageUrl']){
          _param['imageUrl'] = _share['imageUrl'];
        }
        Util.log('app.js分享参数',_param,'channel:',channel);
        return _param;
      };
      config.fieldMap = config.fieldMap || false;
      return xhbPage(config)
    };
    /**
     * 获取配置信息
     */
    Data.getDictConfig('pageConfig',false,true);

  },
  addEvent: function(name,func){
    let Events = EventMap.get(name);
    let pages  = getCurrentPages();
    let page   = pages[pages.length - 1]['route']; //当前页面路径
    if(!Events){
      Events = {};
    }
    Events[page] = func;
    EventMap.put(name,Events);
  },
  triggerEvent:function(name,details){
    let Events = EventMap.get(name);
    let pages  = getCurrentPages();
    let page   = pages[pages.length - 1]['route']; //当前页面路径
    Util.log('triggerEvent:',name);
    if(Events){
      for(let key in Events){
        if(Events.hasOwnProperty(key)){
          if(key !== page){
            try{
              Events[key](details);
            }catch (e) {}
          }
        }
      }
    }
  },
  extend:function(data,dataExtend){
    let res={};
    for (let key in data) {
      res[key] = data[key];
    }
    for (let key in dataExtend) {
      res[key] = dataExtend[key];
    }
    return res;
  },
});
